package com.google.gwt.livinglife.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.livinglife.client.data.LivingLifeGroupData;
import com.google.gwt.livinglife.client.data.UserIdData;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class CreateGroup {
	private VerticalPanel main_panel = new VerticalPanel();
	private Label name_label = new Label("Name of the group");
	private TextBox name_box = new TextBox();
	private Label description = new Label("Short description");
	private TextArea description_box = new TextArea();
	private Button submit_button = new Button("Create");

	public CreateGroup() {
		main_panel.add(name_label);
		main_panel.add(name_box);
		main_panel.add(description);
		main_panel.add(description_box);
		main_panel.add(submit_button);
		submit_button.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				handleSubmit();
			}
		});
	}
	public void handleSubmit() {
		final LivingLifeGroupData group_data = new LivingLifeGroupData();
		group_data.setName(name_box.getText());
		group_data.setDescription(description_box.getText());
		UserIdData uid_data = new UserIdData();
		LoginInfo login_info = LivingLife.getLogin_info();
		uid_data.setId(login_info.getUser_data().getId());
		uid_data.setNickname(login_info.getUser_data().getNickname());
		if (group_data.getName().isEmpty()) {
			Window.alert("Group name cannot be empty");
			return;
		}
		LivingLifeServiceAsync living_life_service = GWT.create(LivingLifeService.class);
		try {
			living_life_service.addGroup(group_data, uid_data, new AsyncCallback<Long>() {
				@Override
				public void onFailure(Throwable caught) {
					Window.alert("Failed to create the group");
				}
				@Override
				public void onSuccess(Long result) {
					if (result < 0) {
						Window.alert("Sorry, group " + group_data.getName() + " already exists.[" + result + "]");
					} else {
						Window.Location.replace(LivingLife.getGroupIdUrl(result));
					}
				}
			});
		} catch (NotLoggedInException e) {
			// TODO Auto-generated catch block
			Window.alert(e.getMessage());
		}
	}
	public VerticalPanel getMain_panel() {
		return main_panel;
	}
}
